using B.S.NewMedical.Api.Write.Application.Command.Doctor;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Doctor
{
    /// <summary>
    /// 删除单个医生处理器
    /// </summary>
    public class DeleteDoctorHandler : IRequestHandler<DeleteDoctorCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Domain.Appointment.Doctor> _doctorRepository;
        private readonly ILogger<DeleteDoctorHandler> _logger;

        public DeleteDoctorHandler(
            IBaseRepository<Domain.Appointment.Doctor> doctorRepository,
            ILogger<DeleteDoctorHandler> logger)
        {
            _doctorRepository = doctorRepository;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(DeleteDoctorCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询医生
                var doctor = await _doctorRepository.GetValue(request.DoctorId);
                if (doctor == null || doctor.IsDeleted)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到该医生信息",
                        Data = false
                    };
                }

                // 逻辑删除
                doctor.IsDeleted = true;
                doctor.UpdateTime = DateTime.Now;

                // 保存更改
                await _doctorRepository.UpdateAsync(doctor);

                _logger.LogInformation("成功删除医生，ID：{DoctorId}", request.DoctorId);

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除医生成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除医生时发生异常");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = "删除医生失败：" + ex.Message,
                    Data = false
                };
            }
        }
    }
} 